export enum WechatyApiEventType {
  'login',
  'logout',
  'qrcode',
  'error',
  'friend-request',
  'friend-be-confirm',
  'friend-do-confirm',
  'room-join',
  'room-leave',
  'room-removed',
  'room-topic-change',
  'message'
}

// const WechatyApiEventTypes = [
//   'login',
//   'logout',
//   'qrcode',
//   'error',
//   'friend-request',
//   'friend-be-confirm',
//   'friend-do-confirm',
//   'room-join',
//   'room-leave',
//   'room-removed',
//   'room-topic-change',
//   'message'
// ]

export default class WechatEvent {
  private app
  private handlers: Object

  constructor (app) {
    this.app = app

    this.handlers = {}
  }

  route (controller) {
    return this.app.post(`/${this.app.config.wechatApi.apiEventPrefix}`, controller)
  }

  handlerEntrance (ctx, body) {
    this.app.logger.debug(`[egg-wechat-api] handlerEntrance event body`, body)

    if (!body.type) {
      throw new Error('wrong event body')
    }

    let uuid = body.wx
    let eventType = body.type
    let handler = this.handlers[uuid] && this.handlers[uuid][eventType]

    if (handler) {
      return handler(body, ctx)
    } else {
      return ctx.body = {
        err_code: 0,
        err_msg: 'success'
      }
    }
  }

  on (uuid, eventType: WechatyApiEventType, handler) {
    if (!handler || Object.prototype.toString.apply(handler) !== '[object Function]') {
      throw new Error('wrong handler type')
    }

    this.app.logger.debug(`[egg-wechat-api] event on`, eventType)

    if (!this.handlers[uuid]) {
      this.handlers[uuid] = {}
    }

    this.handlers[uuid][eventType] = handler
  }

  once (uuid, eventType: WechatyApiEventType, handler) {
    if (!handler || Object.prototype.toString.apply(handler) !== '[object Function]') {
      throw new Error('wrong handler type')
    }

    this.app.logger.debug(`[egg-wechat-api] event once`, eventType)

    if (!this.handlers[uuid]) {
      this.handlers[uuid] = {}
    }

    this.handlers[uuid][eventType] = (event, ctx) => {
      handler(event, ctx)
      delete this.handlers[uuid][eventType]
    }
  }

  off (uuid, eventType: WechatyApiEventType) {
    this.app.logger.debug(`[egg-wechat-api] event off`, eventType)

    delete this.handlers[uuid][eventType]
  }
}
